package net.tngou.c4j;

import java.util.ArrayList;
import java.util.List;

import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import net.tngou.c4j.model.Style;
import net.tngou.c4j.model.Url;
import net.tngou.c4j.util.StyleUtil;
import net.tngou.c4j.util.UrlUtil;
import net.tngou.crawler.util.JsoupUtil;
import net.tngou.crawler.util.StringUtil;

/**
 * 
 * @author tngou@tngou.net
 *
 */
public class Fetcher {

	
	
	public static String getValue(Element element,String field,String invalid) {
		String value = getValue(element, field);
		String out=getValue(element, invalid);
		if(value==null||out==null)return value;
		return StringUtil.remove(value, out);
		
	}
	
	public static String getValue(Element element,String field) {
		if(StringUtil.isEmpty(field))return null;
		List<Style> styles = StyleUtil.split(field);
		for (Style style : styles) {
			element=extract(style, element);
		}
		return _html(element);
		
	}
	
	/**
	 * 数据提取
	 * @param style
	 * @param element
	 * @return
	 */
	 public static  Element extract(Style style, Element element) {
	
		switch (style.getType()) {
		case "id":
			element=element.getElementById(style.getName());
			break;
		case "class":
			if(element.getElementsByClass(style.getName())==null) return null;
			if(StringUtil.isEmpty(element.getElementsByClass(style.getName()).text())) return null;
			if(element.getElementsByClass(style.getName()).size()<=style.getSize()) return null;
			element=element.getElementsByClass(style.getName()).get(style.getSize());
			break;
		case "tag":
			if(element.getElementsByTag(style.getName())==null) return null;
			if(StringUtil.isEmpty(element.getElementsByTag(style.getName()).text())) return null;
			if(element.getElementsByTag(style.getName()).size()<=style.getSize()) return null;
			element=element.getElementsByTag(style.getName()).get(style.getSize());
			break;
		case "attri":
			String name=style.getName();
			String[] sts = StringUtil.split(name, "=");
			if(sts.length<2) return null;
			if(element.getElementsByAttributeValue(sts[0], sts[1])==null) return null;
			if(element.getElementsByAttributeValue(sts[0], sts[1]).size()<=style.getSize()) return null;
			element=element.getElementsByAttributeValue(sts[0], sts[1]).get(style.getSize());
			break;
		default:
			break;
		}
		return element;
		 
	 }
	 
	 
	 
	 private static  String _html(Element element) {
		String html=JsoupUtil.ImgCapture(element);
		return JsoupUtil.clean(html); 
	}
	

}
